/*
 * Copyright 2009 Tran Nhut Trung.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package org.eclipse.core.databinding.observable.gwt.internal;


import com.google.gwt.user.client.ui.Label;

import org.eclipse.core.databinding.conversion.Converter;
import org.eclipse.core.databinding.conversion.gwt.Converters;

public class ErrorsWidget extends Label{
  private static final String DEFAULT_ERROR_STYLE_NAME = "error";
  private static final String DEFAULT_SUCCESS_STYLE_NAME = "success";
  private static final String NBSP = "&nbsp;";
  
  private String errorStyleName;
  private String successStyleName;
  
  public ErrorsWidget(String errorStyleName, String successStyleName) {
    if (errorStyleName == null){
      errorStyleName = DEFAULT_ERROR_STYLE_NAME;
    }
    if (successStyleName == null){
      successStyleName = DEFAULT_SUCCESS_STYLE_NAME;
    }
    
    this.errorStyleName = errorStyleName;
    this.successStyleName = successStyleName;
  }

  public void setError(Throwable error){
    Converter converter = Converters.getConverter(error.getClass(), String.class);
    if (converter == null){
      System.out.println("WARN: No converter for " + error.getClass().getName());
      setErrorText(error.getMessage());
    }else{
      setErrorText((String)converter.convert(error));
    }
  }
  
  public void setErrorText(String errorText){
    // this.setHTML(errorText);
    this.setText(errorText);
    this.addStyleName(errorStyleName);
    this.removeStyleName(successStyleName);
  }

  public void setSuccessText(String successText){
    // this.setHTML(successText);
    this.setText(successText);
    this.addStyleName(successStyleName);
    this.removeStyleName(errorStyleName);
  }

  public void setHTML(String html) {
    if (html == null){
      html = NBSP;
    }
    if (html.trim().length() == 0){
      html = NBSP;
    }
    if (NBSP.equals(html)){
      this.removeStyleName(errorStyleName);
    }else{
      this.addStyleName(errorStyleName);
    }
    
    // super.setHTML(html);
  }

  public void setText(String text) {
    if (text == null){
      text = "";
    }
    if (text.length() == 0){
      this.removeStyleName(errorStyleName);
    }else{
      this.addStyleName(errorStyleName);
    }
    
    super.setText(text);
  }
}
